
#include <pic18.h>
#include <delays.h>
#include "SysClock.h"
#include "my_macros.h"
#include "printf.h"


unsigned int atd_1_result;
unsigned int atd_2_result;

#define   A_INPUT_1			RA0
#define   A_INPUT_1_DIR		TRISA0

#define   A_INPUT_3			RA3  /* CHANNEL 1 */
#define   A_INPUT_3_DIR		TRISA3

#define   A_INPUT_2			RA2	/* CHANNEL 2 */
#define   A_INPUT_2_DIR		TRISA2

#define   ATD_CHANNEL_1		3
#define   ATD_CHANNEL_2		2

void atd_channel_select ( unsigned char channel )
{
	ADCON0 &= 0xC3; 				  /* clear channel number */

	channel &= 0x0F;
	
	ADCON0 |= (channel << 2);
}

unsigned int atd ( unsigned char channel )
{
	unsigned int atd_result;

	atd_channel_select(channel);

	for(atd_result=0;atd_result<10;atd_result++); /* ~45uS */

	GODONE = 1;
	NOP();
	
	while(GODONE)
		continue;

	atd_result = ADRESL;
	atd_result |= (unsigned int)ADRESH << 8;
	
	return atd_result;
}

/* analog */
void ainp_init ( void )
{
	// ADCS<2:0> = 010 => Fosc/32 = 4uS or Frc = x11
	// 10-BIT A/D CONVERSION RESULT FORMAT == (ADFM = 1)
	// ADON = 1; ATD turn on
	
	ADCON1 = 0;
	//ADCON2 = 0b10111110; //;right justify
	//ADCON2 = 0b10100101; //;right justify
	ADCON2 = 0b10100000; //;right justify
	ADCON0 = 0xC1;					  /* clock source Frc; ATD enable */

	A_INPUT_2_DIR = INPUT;
	A_INPUT_3_DIR = INPUT;
	ANSEL = (unsigned char)1<<ATD_CHANNEL_1;					  /* AN3(RA2) as analog input */
	ANSEL |= (unsigned char)1<<ATD_CHANNEL_2;					  /* AN3(RA3) as analog input */
}

void ainp_drive ( void )
{
	/* if ( !Time_2ms ) */
	/* 	return ; */

	atd_1_result = atd(ATD_CHANNEL_1);
	atd_2_result = atd(ATD_CHANNEL_2);
}
